package org.dousb.doujcodesandbox;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import org.dousb.doujcodesandbox.model.ExecuteCodeRequest;
import org.dousb.doujcodesandbox.model.ExecuteCodeResponse;
import org.dousb.doujcodesandbox.model.ExecuteMessage;
import org.dousb.doujcodesandbox.model.JudgeInfo;
import org.dousb.doujcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * JavaNativeCodeSandbox
 *
 * @author 豆沙包
 * @version 1.0
 * @since 2025-11-02  00:33
 */
public class JavaNativeCodeSandbox implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    /**
     * 执行代码
     *
     * @param request 请求参数
     * @return 执行结果
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        // 获取输入列表、代码和编程语言
        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();
        // 把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //将用户的代码隔离存放
        String userCodePathName = globalCodePathName + File.separator + UUID.randomUUID();
        String globalCodePath = userCodePathName + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, globalCodePath, StandardCharsets.UTF_8);
        System.out.println("生成的Java文件路径：" + userCodeFile.getAbsolutePath());
        //编译用户代码 得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            //执行用户代码
            Process process = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.execute(process, "编译");
            System.out.println("ExecuteMessage,编译:" + executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }
        //执行代码 得到输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodePathName, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);

                //超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时，终止进程");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                ExecuteMessage executeMessage = ProcessUtils.execute(runProcess, "运行");
                System.out.println("ExecuteMessage，运行:" + executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }

        }
        //输出用户提交的题目的信息
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();

        //取用时的最大值 便于判断是否超时
        long maxTime = 0;

        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        //正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();
        //文件清理
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodePathName);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return null;
    }

    /**
     * 获取错误信息
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setOutputList(new ArrayList<>());
        //表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    public static void main(String[] args) {
        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();

        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));

        String code = ResourceUtil.readStr("test/SimpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }
}